package guowei.gulicart.interceptor;

import guowei.common.constant.CartConstant;
import guowei.common.constant.SessionInfo;
import guowei.common.vo.MemberVo;
import guowei.gulicart.vo.CartUserInfo;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * 未登录访问购物车，给一个临时用户cookieid
 */
public class CartInterceptor implements HandlerInterceptor {

    public static final ThreadLocal<CartUserInfo> thread = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        CartUserInfo cartUserInfo = new CartUserInfo();
        HttpSession session = request.getSession();
        MemberVo memberVo = (MemberVo) session.getAttribute(SessionInfo.SESSION_PREFIX);
        if (memberVo != null){
            cartUserInfo.setUserId(memberVo.getId());
        }

        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0){
            for (Cookie cookie:cookies){
                String name = cookie.getName();
                if (name.equals(CartConstant.CART_COOKIE)){
                    cartUserInfo.setUserKey(cookie.getValue());
                    cartUserInfo.setIsTemp(true);
                }
            }
        }

        if (StringUtils.isEmpty(cartUserInfo.getUserKey())){
            String toString = UUID.randomUUID().toString();
            cartUserInfo.setUserKey(toString);
        }
        thread.set(cartUserInfo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        CartUserInfo cartUserInfo = thread.get();

        if (!cartUserInfo.getIsTemp()){
            Cookie cookie = new Cookie(CartConstant.CART_COOKIE, cartUserInfo.getUserKey());
            cookie.setDomain("ganjiuwanle.com");
            cookie.setMaxAge(CartConstant.USER_KEY_TIME);
            response.addCookie(cookie);
        }
    }
}
